<?php

namespace app\admin\controller;
use app\models\ClassRoomModel;
use app\models\CourseModel;
use app\models\GradesDetailsListsModel;
use app\models\GradesDetailsModel;
use app\models\StudentSubjectInfosClassModel;
use app\models\TimetableModel;


/**
 * Class Timetable
 * @package app\admin\controller
 */
class Timetable extends Common
{
    /**
     * 课程管理模型.
     *
     * @var CourseModel
     */
    protected $courseModel;

    /**
     * TimetableModel 课表及点名模型.
     *
     * @var TimetableModel
     */
    protected $timetableModel;

    /**
     * 班级管理列表详情模型.
     *
     * @var GradesDetailsListsModel
     */
    protected $gradesdetaillistModel;

    /**
     * 班级管理详情模型.
     *
     * @var GradesDetailsModel
     */
    protected $gradesdetailModel;

    /**
     * 学生分班排课管理模型.
     *
     * @var StudentSubjectInfosClassModel
     */
    protected $studentsubjectinfosclassModel;


    /**
     * 教室管理模型.
     *
     * @var ClassRoomModel
     */
    protected $classroomModel;

    /**
     * 课表及点名管理.
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $now_day = date("Y-m-d");
        $now_time=strtotime(date("H:i:s"));
		$where = [];
		if(get_current_type() == 4 || get_current_type() == 5){
			$where['campus_id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){
			$where['campus_id'] = ['in',get_current_campus_id()];
		}
		$where['class_date'] = $now_day;
        $result = $this->gradesdetaillistModel->where($where)->select();
        $json_room = [];


        $class_where = [];
        $room_id_list = [];
        $room_name_list = [];
		if(get_current_type() == 4 || get_current_type() == 5){
			$class_where['campus_id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){
			$class_where['campus_id'] = ['in',get_current_campus_id()];
		}
        $class_where['seat_set'] = ['neq',''] ; //是否设置原始排位
        $rooms = $this->classroomModel->where($class_where)->select();
        foreach ($rooms as $key => $value_room){
            $room_id_list[] = $value_room['id'];
            $room_name_list[] = $value_room['class_name'];
        }

        $room_id = [];
        $gradesdetaillist = [];
        foreach ($result as $item => $value){
            if(!in_array($value['class_room_id'],$room_id)){   //如果不存在
                $room_id[] = $value['class_room_id'];
                $room_status = false;
                $cell_room = [];
                $cell_room['room_id'] = $value['class_room_id']; // 教室ID
                $cell_room['room_name'] = $value['class_room']; //教室名字
				if(get_current_type() == 4 || get_current_type() == 5){
					$gradesdetaillist['campus_id'] = get_current_campus_id();
				}elseif (get_current_type() == 2 || get_current_type() == 3){
					$gradesdetaillist['campus_id'] = ['in',get_current_campus_id()];
				}
				$gradesdetaillist['class_date'] = $now_day;
				$gradesdetaillist['class_room_id'] = $value['class_room_id'];
                $result_room = $this->gradesdetaillistModel->where($gradesdetaillist)->select();

                $item_value = [];
                foreach ($result_room as $key => $item){
                    $start_time = strtotime($item['class_subject_start']);  //开始时间
                    $end_time = strtotime($item['class_subject_end']); //结束时间
                    if($now_time >= $start_time && $now_time <= $end_time){  //判断当前时间是否在这个区间内
                        $room_status = true;
                        $item_value = $item;
                        break;
                    }
                }
                if($room_status){
                    $cell_room['teacher'] = $item_value['teacher']; //任课老师
                    $cell_room['room_status'] = 1;  //使用中
                    $cell_room['course_name'] = $this->courseModel->get(['id' => $item_value['course_id']])['course_name'];  //课程名称
                }else{
                    $cell_room['teacher'] = '---'; //任课老师无
                    $cell_room['room_status'] = 0;  //空闲
                    $cell_room['course_name']  = '---'; //无课
                }

                $json_room[] = $cell_room;
            }
        }


        for($i =0; $i < count($room_id_list); $i ++){
            if(!in_array($room_id_list[$i],$room_id)){  //不存在数组中
                $room_id[] = $room_id_list[$i];
                $cell_room = [];
                $cell_room['room_id'] = $room_id_list[$i]; // 教室ID
                $cell_room['room_name'] =  $room_name_list[$i]; //教室名字
                $cell_room['teacher'] = '---'; //任课老师无
                $cell_room['room_status'] = 0;  //空闲
                $cell_room['course_name']  = '---'; //无课
                $json_room[] = $cell_room;
            }

        }

        /***********************************/
        /*
        $room_id = [];
        foreach ($result as $item => $value){
            if(!in_array($value['class_room_id'],$room_id)){   //如果不存在
                $room_id[] = $value['class_room_id'];
                $room_status = false;
                $cell_room = [];
                $cell_room['room_id'] = $value['class_room_id']; // 教室ID
                $cell_room['room_name'] = $value['class_room']; //教室名字
                $result_room = $this->gradesdetaillistModel->where(['class_date' => $now_day, 'class_room_id' => $value['class_room_id']])->select();

                $item_value = [];
                foreach ($result_room as $key => $item){
                    $start_time = strtotime($item['class_subject_start']);  //开始时间
                    $end_time = strtotime($item['class_subject_end']); //结束时间
                    if($now_time >= $start_time && $now_time <= $end_time){  //判断当前时间是否在这个区间内
                        $room_status = true;
                        $item_value = $item;
                        break;
                    }
                }
                if($room_status){
                    $cell_room['teacher'] = $item_value['teacher']; //任课老师
                    $cell_room['room_status'] = 1;  //使用中
                    $cell_room['course_name'] = $this->courseModel->get(['id' => $item_value['course_id']])['course_name'];  //课程名称
                }else{
                    $cell_room['teacher'] = '---'; //任课老师无
                    $cell_room['room_status'] = 0;  //空闲
                    $cell_room['course_name']  = '---'; //无课
                }

                $json_room[] = $cell_room;
            }
        }
        */
        /*******************************/



        if(count($room_id) > 0){
            session('room_id', $room_id[0]);
        }
        $json_room_data = json_encode($json_room);
        return $this->fetch('',[ 'jsonroom' => $json_room_data]);
    }

    public function updatesession(){
        if ($this->request->isAjax()) {
            $data = input('post.');
            $room_id  = $data['room_id'];
            session('room_id', $room_id);
            $this->success('', '', '', 1);
        }

    }

    public function getlists()
    {
        if ($this->request->isAjax()) {
            $room_id = session('room_id');
            $param = $this->request->param();
            $list = $this->timetableModel->getTimetableLists($param,$room_id);
            $this->success('success', '', $list, 0);
        }

        return $this->fetch();
    }


    /**
     * 添加课表及点名.
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $data['campus_id'] = get_current_campus_id();
            $data['cost_type'] = 89;
            $data['price'] = $data['price'] * 100;
            $res = $this->timetableModel->save($data);
            $course['id'] = $this->timetableModel->id;
            $course['course_name'] = $this->timetableModel->course_name;
            if (!$res) {
                $this->error('添加课表及点名失败', null, '', 1);
            }
            $this->success('添加成功', '', $course, 1);
        }
        $this->dictionary();
        return $this->fetch('',['year'=>date('Y')]);
    }

    /**
     * 改变状态
     *
     * @return \think\response\Json
     */
    public function timetable_check_status()
    {
        if (request()->isPost()) {
            try {
                $data = input('post.');
                if ($data['status'] == 0) {
                    $msg = '禁用';
                } else {
                    $msg = '启用';
                }
                $this->timetableModel->save($data,['id'=>$data['id']]);
                return json(['code' => 0, 'msg' => $msg]);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
        }
    }

    /**
     * 实例化.
     * @return bool|void
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->timetableModel = new TimetableModel();
        $this->studentsubjectinfosclassModel = new StudentSubjectInfosClassModel();
        $this->gradesdetaillistModel = new GradesDetailsListsModel();
        $this->gradesdetailModel = new GradesDetailsModel();
        $this->courseModel = new CourseModel();
        $this->classroomModel = new ClassRoomModel();
    }
}
